<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-2
 * Time: 上午9:44
 */

namespace common\members\wodrow\widgets\group_checkbox;


use yii\helpers\ArrayHelper;
use yii\widgets\InputWidget;

/**
 * Class GroupCheckBox
 * @package common\widgets\wodrow\group_checkbox
 */
class GroupCheckBox extends InputWidget
{
    public $group_atttibute = null;
    public $parent_attribute = null;
    public $show_attribute = null;

    /*$show_attribute = [
        ['group' => 'g1', 'name' => "n1", 'value' => 1, 'checked' => true, 'parent' => null,],
        ['group' => 'g2', 'name' => "n2", 'value' => 2, 'checked' => true, 'parent' => null,],
        ['group' => 'g2', 'name' => "n3", 'value' => 3, 'checked' => true, 'parent' => 2,],
        ['group' => 'g2', 'name' => "n4", 'value' => 4, 'checked' => false, 'parent' => 2,],
        ['group' => 'g2', 'name' => "n5", 'value' => 5, 'checked' => true, 'parent' => null,],
    ];*/
    public function run()
    {
        $model = $this->model;
        $attribute = $this->attribute;
        $show_attribute = $this->show_attribute;
        $model->$show_attribute = $this->addNewKeyValue($model->$show_attribute, 'parallelNodeHasChildrens', false);
        $model->$show_attribute = \common\components\tools\ArrayHelper::groupBy($model->$show_attribute, 'group');
        foreach ($model->$show_attribute as $k => $v){
            $model->$show_attribute[$k] = \common\components\tools\ArrayHelper::toTree($v, 'value', 'parent');
        }
        foreach ($model->$show_attribute as $k => $v){
            $model->$show_attribute[$k] = $this->checkParallelNodeHasChildrens($v);
        }
        return $this->render('index', [
            'model' => $model,
            'attribute' => $attribute,
            'show_attribute' => $show_attribute,
        ]);
    }

    protected function addNewKeyValue($data, $key, $value = null)
    {
        foreach ($data as $k => $v){
            $data[$k][$key] = $value;
        }
        return $data;
    }

    protected function checkParallelNodeHasChildrens($tree, $keyChildrens = 'childrens')
    {
        foreach ($tree as $k => $v){
            if ($v[$keyChildrens]){
                foreach ($tree as $k1 => $v1){
                    $tree[$k1]['parallelNodeHasChildrens'] = true;
                }
                $tree[$k][$keyChildrens] = $this->checkParallelNodeHasChildrens($v[$keyChildrens], $keyChildrens);
            }
        }
        return $tree;
    }
}